﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.Administration;
using Microsoft.BusinessData.Infrastructure.SecureStore;
using Microsoft.Office.SecureStoreService.Server;
using System.Diagnostics;
using Microsoft.SharePoint.Administration.Claims;

namespace Diplo.Twitter
{
    /// <summary>
    /// Quick and dirty implementation of IOAuthData that loads and saves data into an example XML file
    /// </summary>
    /// <remarks>
    /// For example only - don't use in production without making much more robust!
    /// </remarks>
    public class OAuthSecureStoreData : IOAuthData
    {

        public string AccountName { get; set; }

        public string ScreenName { get; set; }

        public string Token { get; set; }

        public string TokenSecret { get; set; }

        public string UserID { get; set; }

        public bool IsAuthenticated { get; set; }

        public OAuthSecureStoreData()
        {
        }

        /// <summary>
        /// Loads the data from the Secure Store Service
        /// </summary>
        /// <param name="accountname">Login name of the account to get the twitter settings form.</param>
        public OAuthSecureStoreData(string accountname)
        {
            this.AccountName = accountname;

            // Get the default Secure Store Service provider.
            ISecureStoreProvider provider = SecureStoreProviderFactory.Create();
            if (provider == null)
            {
                throw new InvalidOperationException("Unable to get an ISecureStoreProvider");
            }

            ISecureStoreServiceContext providerContext = provider as ISecureStoreServiceContext;
            providerContext.Context = SPServiceContext.GetContext(Helper.GetCentralAdminSite());

            try
            {
                using (SecureStoreCredentialCollection creds = provider.GetCredentials(Constants.AppIDSecureStoreTwitterSupport))
                {
                    if (creds != null)
                    {
                        foreach (SecureStoreCredential cred in creds)
                        {
                            switch (cred.CredentialType)
                            {
                                case SecureStoreCredentialType.UserName:
                                    this.ScreenName = cred.Credential.GetStringFromSecureString();
                                    break;
                                case SecureStoreCredentialType.Generic:
                                    this.UserID = cred.Credential.GetStringFromSecureString();
                                    break;
                                case SecureStoreCredentialType.Key:
                                    this.Token = cred.Credential.GetStringFromSecureString();
                                    break;
                                case SecureStoreCredentialType.Password:
                                    this.TokenSecret = cred.Credential.GetStringFromSecureString();
                                    break;
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(ScreenName) &&
                !string.IsNullOrEmpty(this.Token) &&
                !string.IsNullOrEmpty(this.TokenSecret) &&
                !string.IsNullOrEmpty(this.UserID))
                {
                    IsAuthenticated = true;
                }
                else
                {
                    IsAuthenticated = false;
                }

            }
            catch (SecureStoreServiceCredentialsNotFoundException ex)
            {
                IsAuthenticated = false;
            }


        }

        /// <summary>
        /// Saves the data to the secure store
        /// </summary>
        public void Save()
        {
            IList<ISecureStoreCredential> creds = new List<ISecureStoreCredential>(4);
            creds.Add(new SecureStoreCredential(this.ScreenName.MakeSecureString(), SecureStoreCredentialType.UserName));
            creds.Add(new SecureStoreCredential(this.UserID.MakeSecureString(), SecureStoreCredentialType.Generic));
            creds.Add(new SecureStoreCredential(this.Token.MakeSecureString(), SecureStoreCredentialType.Key));
            creds.Add(new SecureStoreCredential(this.TokenSecret.MakeSecureString(), SecureStoreCredentialType.Password));

            using (SecureStoreCredentialCollection credentials = new SecureStoreCredentialCollection(creds))
            {
                SecureStoreServiceProxy ssp = new SecureStoreServiceProxy();
                ISecureStore iss = ssp.GetSecureStore(SPServiceContext.Current);
                iss.SetCredentials(Constants.AppIDSecureStoreTwitterSupport, credentials);
            }


        }

    }

}
